import 'dart:convert';

import 'package:crypto/crypto.dart';
import 'package:get/get.dart';
import 'package:meiyunapp/common/url_base.dart';

import '../api_service.dart';
import 'base_entity.dart';
import 'base_list_entity.dart';
import 'error_entity.dart';

class BaseGetConnect extends GetConnect {
  late String appId;
  late String appkey;
  String nonceStr = "ssBbeJEy1aQlZhE4KqUQ";
  DateTime now = DateTime.now();

  BaseGetConnect() {
    appId = "meiyunAdmin";
    appkey = "meiyunAdmin20210603UjnrUaGRZYAvL44ajuDqmR56IIIC";
  }

  @override
  void onInit() {
    super.onInit();

    httpClient.baseUrl = UrlBase.getBaseUrl();

    httpClient.addAuthenticator<dynamic>((request) async {
      request.headers.addAll(getHead());
      return request;
    });
  }

  Future<BaseListEntity<T>> requestList<T>(
    String path, {
    Method method = Method.POST,
    dynamic params,
  }) async {
    Response response = await httpClient.request(path, "POST", body: params);

    if (response.statusCode == 200) {
      BaseListEntity<T> entity = BaseListEntity<T>.fromJson(response.body);
      return Future.value(entity);
    } else {
      BaseListEntity<T> error = BaseListEntity(
          state: 999, msg: "", errorEntity: errorHandler(response), data: []);
      return Future.value(error);
    }
  }

  Future<BaseEntity<T>> requestData<T>(
    String path, {
    Method method = Method.POST,
    dynamic params,
  }) async {
    Response response = await httpClient.request(path, "POST", body: params);

    if (response.statusCode == 200) {
      BaseEntity<T> entity = BaseEntity<T>.fromJson(response.body);
      return Future.value(entity);
    } else {
      BaseEntity<T> error = BaseEntity(
          state: 999,
          msg: "",
          errorEntity: errorHandler(response),
          data: Object as T);
      return Future.value(error);
    }
  }

  dynamic errorHandler(Response response) {
    int? errCode = response.statusCode;
    switch (errCode) {
      case 400:
        {
          return ErrorEntity(code: errCode!, message: "请求语法错误");
        }
      case 403:
        {
          return ErrorEntity(code: errCode!, message: "服务器拒绝执行");
        }
      case 404:
        {
          return ErrorEntity(code: errCode!, message: "无法连接服务器");
        }
      case 405:
        {
          return ErrorEntity(code: errCode!, message: "请求方法被禁止");
        }
      case 500:
        {
          return ErrorEntity(code: errCode!, message: "服务器内部错误");
        }
      case 502:
        {
          return ErrorEntity(code: errCode!, message: "无效的请求");
        }
      case 503:
        {
          return ErrorEntity(code: errCode!, message: "服务器挂了");
        }
      case 505:
        {
          return ErrorEntity(code: errCode!, message: "不支持HTTP协议请求");
        }
      default:
        {
          return ErrorEntity(code: errCode!, message: "未知错误");
        }
    }
  }

  getHead() {
    var head = <String, String>{};

    num timestamp = now.millisecondsSinceEpoch;
    String value =
        "appId=$appId&nonceStr=$nonceStr&timestamp=$timestamp$appkey";

    String sign = generateMd5(value).toUpperCase();

    head["appId"] = appId;
    head["nonceStr"] = nonceStr;
    head["timestamp"] = "$timestamp";
    head["sign"] = sign;

    return head;
  }

  String generateMd5(String data) {
    var content = const Utf8Encoder().convert(data);
    var digest = md5.convert(content);
    return digest.toString();
  }
}
